import yaml
from appium.webdriver.webdriver import WebDriver
from selenium.webdriver.common.by import By


class BasePage:
    # 类变量 driver
    _driver: WebDriver
    # 弹窗黑名单
    _black_list = [(By.ID, "iv_close")]

    # 这里我们不构造driver,构造driver的工作放在了APP层
    def __init__(self, driver: WebDriver = None):
        self._driver = driver

    def find(self, By, locator):
        try:
            # 如果没有查找到元素 （遇到了弹窗），就会抛出异常
            element = self._driver.find_element(By, locator)
            return element
        except:
            # 捕获异常，从黑名堂中查找，进行关闭弹窗
            for black in self._black_list:
                elements = self._driver.find_elements(*black)
                if len(elements) > 0:
                    elements[0].click()
                    break

            # 弹窗关闭，进行执行后续操作
            return self.find(By, locator)

    # 操作步骤的数据驱动封装
    def steps(self, path):
        with open(path) as f:
            steps: list[dict] = yaml.safe_load(f)

        element = None
        #   循环执行
        for step in steps:
            if 'by' in step.keys():
                element = self.find(step['by'], step['locator'])
            if 'action' in step.keys():
                action = step['action']
                if action == 'click':
                    element.click()
